#!/bin/bash -x
# DNS-SD Bonjour service discovery for Time Machine volumes

if [[ -z $1 ]]; then
        printf 'Must supply a path\n'
        exit 1
fi

# We want to advertise a consistent volume UUID that will survive reprovisions.
zone_uuid=$(zonename)
bonjour_name="$(hostname -s).local"
dataset=$(printf 'zones/%s/%s' "$zone_uuid "$(sed 's#/$##' <<< "$1"))
tm_guid=$(zfs get -Ho value guid zones/$zone_uuid/$dataset)
share_uuid=$(uuid -v 3 ns:URL "smb://${bonjour_name}/${tm_guid}")

pkill dns-sd

svcadm enable -s dns/multicast

# Advertise ssh. Optional.
/usr/bin/dns-sd -R "${bonjour_name}" _ssh._tcp local 22 &

# Advertise SMB
/usr/bin/dns-sd -R "${bonjour_name}" _smb._tcp local 445 &

# Advertise Automatic Disk, for time machine
# sys= is for system wide options
# dkN= is for disk specific options
# See http://netatalk.sourceforge.net/wiki/index.php/Bonjour_record_adisk_adVF_values
/usr/bin/dns-sd -R "${bonjour_name}" _adisk._tcp local 445 'sys=adVF=0x100' "dk0=adVF=0x82,adVN=TimeMachine,adVU=${share_uuid}" &

# Advertise Device Info
# Specifies Finder icon. Run the following on macOS to get a list of types
# plutil -convert json -r -o - - < /System/Library/CoreServices/CoreTypes.bundle/Contents/Info.plist | json UTExportedTypeDeclarations | json -a -c 'this.UTTypeTagSpecification' UTTypeIconFile UTTypeTagSpecification
/usr/bin/dns-sd -R "${bonjour_name}" _device-info._tcp local 9 model=MacPro7,1 ecolor=226,226,224 &